const http = require('http')
const fs = require('fs')
const URL = require('url')
const template = require('art-template')

var comments = [
    {
        name: 'Tom1',
        message: '今天天气真不错',
        date: '2020-07-01'
    },
    {
        name: 'Tom2',
        message: '今天天气真不错',
        date: '2020-07-02'
    },
    {
        name: 'Tom3',
        message: '今天天气真不错',
        date: '2020-07-03'
    },
    {
        name: 'Tom4',
        message: '今天天气真不错',
        date: '2020-07-04'
    },
    {
        name: 'Tom5',
        message: '今天天气真不错',
        date: '2020-07-05'
    },
]

http.createServer((req,res)=>{
    var url = req.url
    var pathObj = URL.parse(url,true)
    if(url == '/'){
        fs.readFile('html/03.index.html',(err,data)=>{
            if(err){
                return res.end("404 not found")
            } 
            // res.setHeader('Content-Type','text/html;charset=utf-8')
            var com = template.render(data.toString(),{
                comments: comments
            })
            res.end(com)
        })
    } else if(url == '/post'){
        fs.readFile('html/03.post.html',(err,data)=>{
            if(err){
                return res.end("404 not found")
            }
            res.end(data)
        })
    
    } else if(pathObj.pathname == '/pinglun'){
        var cmt = pathObj.query
        var newdate = new Date()
        cmt.date = newdate.getFullYear().toString() + "-" + (newdate.getMonth()+1).toString() + "-" + newdate.getDate().toString()
        comments.unshift(cmt)

        res.statusCode = 302 // 状态码设置为 302（临时重定向）
        res.setHeader('Location','/') // 在响应头中通过 Location告诉客户端往哪重定向
        /* 

        */
        res.end()
    } else if(url.indexOf('/css/') == 0){
        fs.readFile('.'+url,(err,data)=>{
            if(err){
                return res.end("404 not found")
            }
            res.end(data)
        })
    } else if(url.indexOf('/html/') == 0){
        fs.readFile('.'+url,(err,data)=>{
            if(err){
                return res.end("404 not found")
            }
            res.end(data)
        })
    } else{
        fs.readFile('./html/404.html',(err,data)=>{
            return res.end(data)
        })
    }
    
    // res.end("this is 03.app.js")
}).listen(8030,()=>{
    console.log("***")
})